/**
 * 数组迭代
*/
export function generatorArr<T extends any[]>(arr: T) {
  type ICallback<T, U> = (data: T, next: U) => void

  const useCallbacks: Array<ICallback<T[number], typeof next>> = []
  let nextIndex = 0

  // 注册
  const next = () => {
    console.log(nextIndex, useCallbacks.length - 1)
    if (nextIndex > useCallbacks.length - 1) return

    useCallbacks[nextIndex](arr[nextIndex], () => {
      nextIndex++
      next()
    })
  }

  const use = (callback: ICallback<T[number], typeof next>) => {
    useCallbacks.push((...args: Parameters<typeof callback>) => {
      callback(...args)
    })
  }

  return {
    use,
    next
  }
}

/**
 * requestAnimationFrame 动画
*/
export function useAnimationFrame(callback: <T extends () => void>(param: T) => void, frame = 60) {
  let sTime = Date.now(),
   fTime = 1000 / frame, // 1frame = xx s
   isStop = false

  const cb = () => {
    const eTime = Date.now()
    if (isStop) return

    if (eTime - sTime >= fTime) {
      callback(clear)
      sTime = eTime
    }

    console.log('requestAnimation程序执行...')
    window.requestAnimationFrame(cb)
  }

  const walk = () => {
    window.requestAnimationFrame(cb)
  }

  const clear = () => {
    isStop = true
  }

  const start = () => {
    isStop = false
    walk()
  }

  return start
}
